package com.fiap.activities;

import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.fiap.functions.UserFunctions;
import com.fiap.sqlite.DatabaseHelper;

public class RegisterActivity extends Activity {
	
	private TextView linkLoginScreen;
	private EditText txtFullName;
    private EditText txtEmail;
    private EditText txtPassword;
    private EditText txtNickname;
    private Button btnRegister;
    private TextView registerErrorMsg;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);
        
        prepareScreen();
        
        // Listening to Login Screen link
        linkLoginScreen.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View arg0) {
				Intent i = new Intent(getApplicationContext(), LoginActivity.class);
                startActivity(i);
                
                // Close Registration View
				finish();
			}
		});
        
        
        btnRegister.setOnClickListener(new View.OnClickListener() {         
            public void onClick(View view) {
                String fullname = txtFullName.getText().toString();
                String email = txtEmail.getText().toString();
                String password = txtPassword.getText().toString();
                String nickname = txtNickname.getText().toString();
                if(fullname.equals("") || email.equals("") || password.equals("") || nickname.equals("")) {
                	registerErrorMsg.setText("Informações inválidas");
                    registerErrorMsg.setVisibility(0);
                    return;
                } else if(!validateEmail(email)) {
                	registerErrorMsg.setText("Email inválido");
                    registerErrorMsg.setVisibility(0);
                    return;
                }
                
                UserFunctions userFunction = new UserFunctions();
                JSONObject json = userFunction.registerUser(fullname, email, password, nickname);
                 
                try {
                    if (json.getString("success") != null) {
                        registerErrorMsg.setText("");
                        String res = json.getString("success"); 
                        if(Integer.parseInt(res) == 1){
                            // user successfully registred
                            DatabaseHelper db = new DatabaseHelper(getApplicationContext());
                            JSONObject json_user = json.getJSONObject("user");	
                             
                            // Clear all previous data in database
                            userFunction.logoutUser(getApplicationContext());
                            db.addUser(json_user.getLong("id"), json_user.getString("fullname"), 
                            		json_user.getString("email"));                        

                            Intent initialInfo = new Intent(getApplicationContext(), InitialInfoActivity.class);
                            // Close all views before launching
                            initialInfo.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            initialInfo.putExtra("firstTime", true);
                            startActivity(initialInfo);
                            finish();
                        }else{
                        	String errorMessage = json.getString("error_msg");
                            registerErrorMsg.setText(errorMessage);
                            registerErrorMsg.setVisibility(0);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        
        
    }
    
    private void prepareScreen() {
    	linkLoginScreen = (TextView) findViewById(R.id.link_skip_step);
    	txtFullName = (EditText) findViewById(R.id.reg_fullname);
    	txtEmail = (EditText) findViewById(R.id.reg_email);
    	txtPassword = (EditText) findViewById(R.id.reg_password);
    	txtNickname = (EditText) findViewById(R.id.reg_nickname);
    	btnRegister = (Button) findViewById(R.id.btnSaveInfo);
    	registerErrorMsg = (TextView) findViewById(R.id.register_error_msg);
	}

	public void register(View v) {
    	Intent i = new Intent(getApplicationContext(), InitialInfoActivity.class);
		startActivity(i);
    }
    
	public boolean validateEmail(String email){
		   // Input the string for validation
		   // String email = "xyz@.com";
		   // Set the email pattern string
		   Pattern p = Pattern.compile(".+@.+\\.[a-z]+");

		   // Match the given string with the pattern
		   Matcher m = p.matcher(email);

		   // check whether match is found
		   boolean matchFound = m.matches();

		   StringTokenizer st = new StringTokenizer(email, ".");
		   String lastToken = null;
		   while (st.hasMoreTokens()) {
		      lastToken = st.nextToken();
		   }

		   if (matchFound && lastToken.length() >= 2
		      && email.length() - 1 != lastToken.length()) {

		      // validate the country code
		      return true;
		   }
		   else return false;
		}
}